package com.zzs.client.service.impl;

import com.zzs.client.convert.CodeSubmitConvert;
import com.zzs.client.dao.mysql.CodeSubmitMapper;
import com.zzs.client.pojo.dto.submit.CodeSubmitDTO;
import com.zzs.client.pojo.vo.submit.CodeSubmitDetailVO;
import com.zzs.client.pojo.vo.submit.CodeSubmitVO;
import com.zzs.client.service.CodeSubmitService;
import com.zzs.common.core.constant.RabbitConsts;
import com.zzs.common.core.constant.RedisKeyConsts;
import com.zzs.common.core.entity.msg.CodeSubmitMessage;
import com.zzs.common.core.entity.mysql.CodeSubmitDO;
import com.zzs.common.core.enums.ResponseCode;
import com.zzs.common.core.response.PageResult;
import com.zzs.common.redis.service.RedisService;
import com.zzs.common.security.exception.ServiceException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zzs
 * @date 2025/04/01
 */
@Service
public class CodeSubmitServiceImpl implements CodeSubmitService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private CodeSubmitConvert codeSubmitConvert;
    @Autowired
    private CodeSubmitMapper codeSubmitMapper;

    @Override
    public String submit(CodeSubmitDTO codeSubmitDTO, long userId) {
        if (redisService.hasKey(RedisKeyConsts.getJudgingKey(userId))) {
            throw new ServiceException(ResponseCode.JUDGING, "正在判题中, 请稍后再试");
        }
        CodeSubmitMessage codeSubmitMessage = codeSubmitConvert.dtoToMessage(codeSubmitDTO, userId);
//        把判题请求发送到消息队列中
        rabbitTemplate.convertAndSend(RabbitConsts.JAVA_EXCHANGE, RabbitConsts.JAVA_ROUTING_KEY, codeSubmitMessage);
//        设置一个标志位, 只要这个标志位存在, 那么说明正在判题中, 在此期间用户不允许再次提交代码
        redisService.saveValue(RedisKeyConsts.getJudgingKey(userId), 1, RedisKeyConsts.getJudgingExpireTime(), RedisKeyConsts.getJudgingTimeUnit());
//        本次判题结果的id
        return codeSubmitMessage.getId() + "";
    }

    @Override
    public CodeSubmitDetailVO getCodeSubmitDetail(long codeSubmitId) {
        CodeSubmitDO codeSubmitDO = codeSubmitMapper.getCodeSubmitDetail(codeSubmitId);
        if (codeSubmitDO == null) {
            throw new ServiceException(ResponseCode.NOT_FOUND, "提交记录不存在");
        }
        return codeSubmitConvert.doToVo(codeSubmitDO);
    }

    @Override
    public PageResult<CodeSubmitVO> listCodeSubmits(long userId, long problemId) {
        List<CodeSubmitDO> codeSubmitDOList = codeSubmitMapper.listCodeSubmits(userId, problemId);
        if (codeSubmitDOList == null || codeSubmitDOList.isEmpty()) {
            return PageResult.empty(0);
        }
        List<CodeSubmitVO> codeSubmitVOList = codeSubmitConvert.doListToVoList(codeSubmitDOList);
        return PageResult.success(codeSubmitVOList.size(), codeSubmitVOList);
    }
}
